package org.fing.edu.uy.esbadp.modules.adpMotorMonitor.wsdl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;

import org.fing.edu.uy.esbadp.logger.LoggerADP;
import org.ow2.easywsdl.schema.SchemaFactory;
import org.ow2.easywsdl.schema.api.Import;
import org.ow2.easywsdl.schema.api.Schema;
import org.ow2.easywsdl.schema.api.SchemaWriter;
import org.ow2.easywsdl.wsdl.WSDLFactory;
import org.ow2.easywsdl.wsdl.api.Description;
import org.ow2.easywsdl.wsdl.api.Types;
import org.ow2.easywsdl.wsdl.api.WSDLReader;
import org.ow2.easywsdl.wsdl.api.WSDLWriter;

public class StoreWsdl {
	
	private static final java.util.logging.Logger logger = LoggerADP.getLogger(StoreWsdl.class.getSimpleName());
	
	/**
	 * storeWsdl --> Funcion encargada de salvar en disco el wsdl de la url pasada como parametro.
	 * @param url - Localizacion del wsdl actual (pueder ser una url o un path).
	 * @param pathToSave - Path absoluto donde se desea generar el archivo resultante.
	 * @param fileName - Nombre con el cual se desea guardar el wsdl.
	 * @return - Return boolean el cual indicate si el archivo fue salvado correctamente.
	 */
	public static boolean storeWsdl(String url, String pathToSave, String fileName) {
        boolean success = false;
		try {
			if (logger.isLoggable(Level.FINE)) {
	            logger.log(Level.FINE, "storeWsdl: [{0}, {1}, {2}] ", new Object[]{url, pathToSave, fileName});
	        }
			
			WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
			WSDLWriter writer = WSDLFactory.newInstance().newWSDLWriter();
			SchemaWriter writerSchema = SchemaFactory.newInstance().newSchemaWriter();
			
			Description defs1 = reader.read(new URL(url));
			Types types = defs1.getTypes();
			List<Schema> schemas = types.getSchemas();
			
			for(Schema schema : schemas){
				int index = 1;
				for(Import importFile : schema.getImports()) {
					StringBuilder fileNameOut = new StringBuilder(pathToSave);
					fileNameOut.append("/").append(fileName).append(".xsd").append(index);
					OutputStream outStream = new FileOutputStream(new File(new URL(fileNameOut.toString()).toURI()));
					writerSchema.writeSchema(importFile.getSchema(), outStream);
					outStream.close();
					importFile.setLocationURI(new URI("./" + fileName + ".xsd" + index));
					index++;
				}
			}
			
			String wsdlFileStr = writer.writeWSDL(defs1);
			saveWsdlToFile(wsdlFileStr, pathToSave + "/" + fileName + ".xml");	
			success = true;			
        }catch (java.net.ConnectException ex) {
        	logger.log(Level.SEVERE, "Imposible to connect with ->" + url);
		}catch(Exception ex){
			logger.log(Level.SEVERE, "Exception in storeWsdl.", ex);
		}
		return success;
	}

	private static void saveWsdlToFile(String wsdlFileStr, String filePath) throws Exception {
		OutputStream outStream = new FileOutputStream(new File(new URL(filePath).toURI()));
		outStream.write(wsdlFileStr.getBytes("UTF-8"));
		outStream.close();
	}

}
